<?php

namespace app\index\controller;

use app\common\controller\HomeBase;
use think\Db;
use QL\QueryList;

class Detail extends HomeBase {

    
    public function index() {
        $id = input('param.id');
        
        if($id){
            $data = Db::name('Movies')->find($id);
            if(!$data){
                abort(404, '电影不存在'); 
            }else{
                $sign = getSign($data['pid']);  //导航
                $data['content'] = str_replace ('<!-- 不显示封面图片 -->', '',$data['content']);
                
                if($data['true_download']){
                    $link = url('/down/'.$data['id']);
                    $res= QueryList::Query($data['download'],array(
                            'link' => array('.dl-btn-z','href'),
                        ))->data;
//                    p($res);
                    foreach ($res as $k=>$v){
                        $data['download'] = str_replace($v['link'], $link, $data['download']);
                    }
                
                }
                //高效率随机获取同类型电影
                $data2 = Db::query('SELECT m.id,m.title,m.cover_image FROM zhuzong_movies AS m   
JOIN   
(SELECT   
    ROUND(  
        RAND() * ((SELECT MAX(id) FROM zhuzong_movies)-(SELECT MIN(id) FROM zhuzong_movies))   
        + (SELECT MIN(id) FROM zhuzong_movies)  
    ) AS id  
) AS m2   
WHERE m.id>=m2.id and m.pid='.$data['pid'].' limit 14');
            }  
        }else{
            abort(404, '电影不存在');
        }
        
        $data3 = $this->moreMovies($data['pid'],$id);
        
        //增加浏览量
        Db::name('Movies')->where(['id'=>$id])->setInc('click');
                
        return $this->fetch('',['data'=>$data,'data2'=>$data2,'data3'=>$data3,'sign'=>$sign,'title'=>$data['title']]);
    }
    
    
    //推荐该类其他电影
    public function moreMovies ($pid,$id,$page=0) {
        $num = $page*12;
        $limit = "$num,12";
        $data = Db::name('Movies')->cache(3600)->field('id,title,cover_image,add_time')->where(['pid'=>$pid,'id'=>['neq',$id]])->order('add_time desc')->limit($limit)->select();
        
        if($this->request->isAjax()){
            $this->view->engine->layout(false); 
            return $this->fetch('recommended',['data'=>$data]);
        }else{
            return $data;
        }
    }
}
